import { formatTimeToStr } from '@/utils/date'
import { store } from '@/pinia'
import { dictStore } from '@/pinia/modules/dict'
const dictStoreData = dictStore(store) // 这里需要重新引入store注册 否则会有组件渲染无法找到pinia问题

export const formatBoolean = bool => {
  if (bool !== null) {
    return bool ? '是' : '否'
  } else {
    return ''
  }
}
export const formatDate = time => {
  if (time !== null && time !== '') {
    var date = new Date(time)
    return formatTimeToStr(date, 'yyyy-MM-dd hh:mm:ss')
  } else {
    return ''
  }
}

export const filterDict = (value, options) => {
  const rowLabel = options && options.filter(item => item.value === value)
  return rowLabel && rowLabel[0] && rowLabel[0].label
}

export const formatDictCode = (code, val) => {
  // eslint-disable-next-line eqeqeq
  const target = dictStoreData.dict.find(item => item.code == code)
  if (target && (val || val === 0 || val === '0') && val !== '--') {
    // if (Array.isArray(val)) {
    // 如果是数组
    let res = ''
    val
      .toString()
      .split(',')
      .forEach((item, index) => {
        // eslint-disable-next-line eqeqeq
        const a = target.children.find(item1 => item1.code == item)
        if (a) {
          res += `${index === 0 ? '' : ','}${a.name}`
        } else {
          res += ''
        }
        // eslint-disable-next-line eqeqeq
      })
    return res
  }
  return '--'
}

export const formatMoney = num => {
  return num
    ? String(num).replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')
    : '--'
}

export const formatDetailEmpty = data => {
  if (!!data) {
    let newObj
    if (Array.isArray(data)) {
      newObj = []
      for (let i = 0; i < data.length; i++) {
        //  判断数组中的元素数据类型
        if (Array.isArray(data[i])) {
          //  递归
          newObj[i] = formatDetailEmpty(data[i])
        } else {
          newObj[i] = data[i] || data[i] === 0 ? data[i] : '--'
        }
      }
    } else {
      newObj = {}
      for (let key in data) {
        //  判断对象中的属性值的数据类型
        if (typeof data[key] === 'object' && data[key] !== null) {
          newObj[key] = formatDetailEmpty(data[key])
        } else {
          newObj[key] = data[key] || data[key] === 0 ? data[key] : '--'
        }
      }
    }
    return newObj
  }
}
